const clouddb = require('@hw-agconnect/database-server/dist/index.js');
const agconnect = require('@agconnect/common-server');
const path = require('path');
const { User } = require('./User')



/*
    配置区域
*/
//TODO 将AGC官网下载的配置文件放入resources文件夹下并将文件名替换为真实文件名
const credentialPath = "/resources/agc-apiclient-cloudFunc.json";
// 修改为在管理台创建的存储区名称
let zoneName = "default"

let logger

let mCloudDBZone

class CloudDBZoneWrapper {

    // AGC & 数据库初始化
    constructor(log) {
        logger = log;

        let agcClient;

        try {
            agcClient = agconnect.AGCClient.getInstance();
        } catch (error) {
            agconnect.AGCClient.initialize(agconnect.CredentialParser.toCredential(path.join(__dirname, credentialPath)));
            agcClient = agconnect.AGCClient.getInstance();
        }

        clouddb.AGConnectCloudDB.initialize(agcClient);

        const cloudDBZoneConfig = new clouddb.CloudDBZoneConfig(zoneName);

        const agconnectCloudDB = clouddb.AGConnectCloudDB.getInstance(agcClient);
        mCloudDBZone = agconnectCloudDB.openCloudDBZone(cloudDBZoneConfig);
    }

    // 写入数据，主键相同则更新
    async executeUpsert(data) {
        if (!mCloudDBZone) {
            console.log("CloudDBClient is null, try re-initialize it");
            return;
        }
        try {
            const resp = await mCloudDBZone.executeUpsert(data);
            return resp;
        } catch (error) {
            logger.info('upsertBookInfo=>', error);
            console.warn('upsertBookInfo=>', error)
        }
    }

    // 写入数据，主键相同则报错
    async executeInsert(data) {
        if (!mCloudDBZone) {
            console.log("CloudDBClient is null, try re-initialize it");
            return;
        }
        try {
            const resp = await mCloudDBZone.executeInsert(data);
            return resp;
           } catch (error) {
            logger.info('insertBookInfos=>', error);
            console.warn('insertBookInfos=>', error)
        }
    }

    // 对指定字段的值进行增量操作
    async executeIncrement(data) {
        if (!mCloudDBZone) {
            console.log("CloudDBClient is null, try re-initialize it");
            return;
        }
        let mainKey = data.mainKey;
        let objectName = data.objectName;
        let objectValue = data.objectValue;

        let set = this.setMainKey(mainKey);

        try {
            const operator = clouddb.CloudDBZoneObjectOperator.build(set).increment(objectName, objectValue);
            const updateNum = await mCloudDBZone.executeUpdate(operator);
            logger.info("updateNum=>", updateNum);
            console.log("updateNum=>", updateNum);
            return updateNum;
        } catch (error) {
            logger.info('updateBookInfos=>', error);
            console.warn('updateBookInfos=>', error);
        }
    }

    // 对指定字段的值进行更新操作
    async executeUpdate(data) {
        if (!mCloudDBZone) {
            console.log("CloudDBClient is null, try re-initialize it");
            return;
        }
        let mainKey = data.mainKey;
        let objectName = data.objectName;
        let objectValue = data.objectValue;

        let set = this.setMainKey(mainKey);

        try {
            const operator = clouddb.CloudDBZoneObjectOperator.build(set).update(objectName, objectValue);
            const updateNum = await mCloudDBZone.executeUpdate(operator);
            logger.info("updateNum=>", updateNum);
            console.log("updateNum=>", updateNum);
            return updateNum;
        } catch (error) {
            logger.info('updateBookInfos=>', error);
            console.warn('updateBookInfos=>', error);
        }
    }

    // 删除数据
    async excuteDelete(data) {
        if (!mCloudDBZone) {
            console.log("CloudDBClient is null, try re-initialize it");
            return;
        }
        try {
            const resp = await mCloudDBZone.executeDelete(data);
            return resp;
        } catch (error) {
            logger.info('deleteBookInfos=>', error);
            console.warn('deleteBookInfos=>', error);
        }
    }

    // 组装需要插入或删除的数据对象
    getDataList(data) {
        let dataList = [];
        for(var i of data) {
            /** e.g.
                const unit = new unittest();
                unit.setId(i.id);
                unit.setSum(i.sum);
                unit.setName(i.name);
                dataList.push(unit);
            */

            const unit = new User();
            unit.setId(i.id);
            unit.setAccount(i.account);
            unit.setPhoneNum(i.phoneNum);
            unit.setPassword(i.password);
            unit.setToken(i.token);
            unit.setTime(i.time);
            dataList.push(unit);
        }
        return dataList;

    }

    // 设置需要更新的主键
    setMainKey(mainKey) {
        /** e.g.
            const unit = new unittest();
            unit.setId(mainKey);
            return unit
        */
        const unit = new User();
        unit.setId(mainKey);
        return unit
    }

}

module.exports = CloudDBZoneWrapper;